package com.jumper.property.comparer.starter;

import com.jumper.property.comparer.starter.jpa.JpaLogRepositoryImpl;
import com.jumper.property.comparer.core.support.LogRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.support.TransactionTemplate;

import javax.persistence.EntityManager;

@Slf4j
public class JpaLogAutoConfiguration implements ApplicationContextAware {

    /**
     * Spring容器
     */
    private ApplicationContext ctx;


    /**
     * 注入业务日志仓库
     */
    @Bean
    public LogRepository busOptLogRepository() {
        return getJpaRepository();
    }

    /**
     * Jpa实现
     */
    private LogRepository getJpaRepository() {
        EntityManager entityManager = ctx.getBean(EntityManager.class);
        TransactionTemplate transactionTemplate = ctx.getBean(TransactionTemplate.class);
        return new JpaLogRepositoryImpl(entityManager, transactionTemplate);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx = applicationContext;
    }
}
